#coding=utf-8
import os, sqlite3
from config import ROOTDIR
from utility import str2date

db = os.path.join(ROOTDIR, 'data', 'recorder.sqlite')
con = sqlite3.connect(db) 

def create_db():
    create_update_recorder_sql = \
    '''
        create table if not exists update_records(
            id integer primary key autoincrement,
            code varchar(20), 
            update_price_on date,
            update_ts_on date,
            update_fqr_on date,
            update_deal_on date)
    '''
    c = con.cursor()
    c.execute(create_update_recorder_sql)
create_db()
       
class UpdateRecorder(object):
    def __init__(self, code):
        self.code = code
    
    def record_exists(self):    
        c = con.cursor()
        c.execute('select id from update_records where code=?',
                 (self.code,))
        r = c.fetchone()
        if r:return True
        else:
            return False
            
    def get_update_ts_on(self):
        c = con.cursor()
        c.execute('select update_ts_on from update_records where code= ?', 
                  (self.code,))
        r = c.fetchone()
        if not r:return None
        return str2date(r[0])
    def set_update_ts_on(self, date):    
        c = con.cursor()
        if self.record_exists():
            c.execute('update update_records set update_ts_on = ? where code = ?', 
                      (date, self.code))
        else:
            c.execute('insert into update_records (code, update_ts_on) values (?, ?)',
                     (self.code, date))
        con.commit()
    update_ts_on = property(fget=get_update_ts_on, fset=set_update_ts_on)
           
